package com.zkingsoft.util;

import java.lang.reflect.Field;
import java.sql.Date;

import javax.servlet.http.HttpServletRequest;

import com.zkingsoft.entity.Entity;

public class RequestBeanUtil {

	public static Entity setProperties(HttpServletRequest request,Entity entity) {
		
		Class clazz = entity.getClass();
		Field[] fields = clazz.getDeclaredFields();//实体所有属性
		for(int i = 0; i < fields.length; i++) {
			Field field = fields[i];
			String fieldName =field.getName();//属性名
			Class fieldType = field.getType();//属性的类型
			String value = request.getParameter(fieldName);
			System.out.println("fieldName = " + fieldName + ",value = " + value);
			if(value != null && !"".equals(value)) {
				field.setAccessible(true);
				try {
					//根据属性的数据类型，进行数据类型转换再设置
					if(fieldType == String.class) {
						field.set(entity, value);
					} else if(fieldType == Integer.class || fieldType == int.class) {
						Integer v = Integer.valueOf(value);
						field.set(entity, v);
					} else if(fieldType == Float.class || fieldType == float.class) {
						Float v = Float.valueOf(value);
						field.set(entity, v);
					}else if(fieldType == Double.class || fieldType == double.class) {
						Double v = Double.valueOf(value);
						field.set(entity, v);
					}else if(fieldType == Date.class) {
						Date v = Date.valueOf(value);
						field.set(entity, v);
					}
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
		}
		return entity;
	}
	
}
